import React, { Component } from 'react'

import { List, AutoSizer } from 'react-virtualized';

import { Toast } from 'antd-mobile';

import { getCurrentCity } from '../../utils'

import NavHeader from '../../components/NavHeader'
import { getCityList, getCityHot } from '../../api/city.js'

import './index.scss'

function formatList(letter) {
    switch (letter) {
        case '#':
            return '当前城市'
        case "hot":
            return '热门城市'
        default:
            return letter.toUpperCase();
    }
}

// 索引（A、B等）的高度
const TITLE_HEIGHT = 36
// 每个城市名称的高度
const NAME_HEIGHT = 50
// 已经开通的地区房源
const HOUSE_CITY = ['北京', "上海", '广州', '深圳']

export default class index extends Component {
    constructor() {
        super()


        this.state = {
            city: [],
            list: [],
            activeIndex: 0
        }
        // 创建ref
        this.cityListComponent = React.createRef();
    }

    clickCity(val) {
        return () => {
            if (HOUSE_CITY.indexOf(val.label) > -1) {
                window.localStorage.setItem('liu_city', JSON.stringify(val));
                this.props.history.go(-1)
                return
            }
            Toast.info('该地区暂未开通 !!!', 1);
        }
    }

    componentDidMount() {
        this.getCityList()
    }

    // 渲染每一行的内容
    rowRenderer = ({
        key,         // Unique key within array of rows
        index,       // 索引号
        isScrolling, // 当前项是否正在滚动中
        isVisible,   // 当前项在List中是可见的
        style        // 重点属性：一定要给每一个行数添加该样式
    }) => {
        // 返回的就是渲染的 数据
        // console.log(this.state.city);
        // console.log(this.state.city[this.state.list[index]]);

        return (
            <div
                key={key}
                style={style}
                className="city"
            >
                <div className="title"> {formatList(this.state.list[index])}</div>
                {this.state.city[this.state.list[index]].map(item => (<div className="name" key={item.value} onClick={this.clickCity(item)}>
                    {item.label}
                </div>))}
            </div>
        )
    }

    // 获取城市信息
    async getCityList() {
        const { data } = await getCityList()
        const { city, list } = this.formatCityData(data.body)

        const { data: res } = await getCityHot()
        city['hot'] = res.body
        list.unshift('hot')

        // 获取当前城市
        const aaa = await getCurrentCity()
        city['#'] = [aaa]
        list.unshift('#')

        this.setState({
            city,
            list,
        })
    }

    // 计算城市每组的高度
    rowHeight = ({ index }) => {
        return this.state.city[this.state.list[index]].length * NAME_HEIGHT + TITLE_HEIGHT
    }

    // 处理数据开头字母
    formatCityData(data) {
        const city = {}
        let list = []
        data.forEach(item => {
            let str = item.short.substr(0, 1)
            if (!city[str]) {
                city[str] = []
            }
            city[str].push(item)
        });
        list = Object.keys(city).sort()
        return {
            city,
            list
        }
    }

    renderCityIndex() {
        return this.state.list.map((item, index) => {
            return (
                <li className="city-index-item" key={item} onClick={() => {
                    this.cityListComponent.current.scrollToRow(index)
                    this.setState({ activeIndex: index })
                }}>
                    {/*判断一下，如果高亮状态的索引等于当前索引，那么就设置高亮样式*/}
                    <span className={this.state.activeIndex === index ? 'index-active' : ''}>{item === 'hot' ? '热' : item.toUpperCase()}</span>
                </li>
            )
        })
    }

    render() {
        return (
            <div className="citylist">
                <NavHeader>选择城市</NavHeader>

                <AutoSizer>
                    {({ width, height }) => (
                        <List
                            ref={this.cityListComponent}
                            // 组件的宽度
                            width={width}
                            // 组件的高度
                            height={height}
                            //一共的长度
                            rowCount={this.state.list.length}
                            // 每行的高度
                            rowHeight={this.rowHeight}
                            // 渲染函数
                            rowRenderer={this.rowRenderer}
                            scrollToAlignment="start"
                        />
                    )
                    }
                </AutoSizer>

                {/* 右侧索引列表 */}
                <ul className="city-index">
                    {
                        this.renderCityIndex()
                    }
                </ul>
            </div>
        )
    }
}
